package com.jeect.filter;

import com.jeect.util.CookieUtil;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import java.util.Enumeration;

import static org.springframework.cloud.netflix.zuul.filters.support.FilterConstants.PRE_TYPE;

@Component
public class UserFilter extends ZuulFilter {
    @Override
    public String filterType() {
        return PRE_TYPE;
    }

    @Override
    public int filterOrder() {
        return 0;
    }

    @Override
    public boolean shouldFilter() {
        return true;
    }

    @Override
    public Object run() {
        RequestContext context = RequestContext.getCurrentContext();
        HttpServletRequest request = context.getRequest();
        Cookie cookie = CookieUtil.get(request,"openid");
        Cookie[] cookies = request.getCookies();
        System.out.println("Filter  is running.......");
        System.out.println("zuul过滤器中的cookies信息为："+ cookies);
//        for(Cookie c:cookies){
//            System.out.println(c);
//        }

//        Enumeration<String> headers = request.getHeaderNames();
//        while (headers.hasMoreElements()) {
//            String name = headers.nextElement();
//            System.out.println(name + ":" + request.getHeader(name));
//        }
//        if(request.getRequestURI().endsWith("/user/login")){
//            context.setSendZuulResponse(true);
//            context.setResponseStatusCode(HttpStatus.ACCEPTED.value());
//            return null;
//        }
        HttpSession session = request.getSession();
        String sessionid = session.getId();
        System.out.println("name="+session.getAttribute("name"));
           // context.addZuulRequestHeader("Cookie","SESSION="+sessionid);
//            if(session!=null && session.getAttribute("authentication")!=null) {
                System.out.println("sessionid=====================" + sessionid);
                context.setSendZuulResponse(true);
                context.setResponseStatusCode(HttpStatus.ACCEPTED.value());
             return null;
//            }else{
//                context.setSendZuulResponse(false);
//                context.setResponseStatusCode(HttpStatus.UNAUTHORIZED.value());
//                return null;
//            }
//        }
//        if (cookie == null || StringUtils.isEmpty(cookie.getValue())) {
//            System.out.println("cookie="+cookie);
//            context.setSendZuulResponse(false);
//            context.setResponseStatusCode(HttpStatus.UNAUTHORIZED.value());
//        }

//
//        context.setSendZuulResponse(true);
//        context.setResponseStatusCode(200);k
//        return null;
    }
}
